//
//  CPOauthViewController.swift
//  weibo
//
//  Created by zcp on 16/5/12.
//  Copyright © 2016年 zcp. All rights reserved.
//

import UIKit
import SVProgressHUD

class CPOauthViewController: UIViewController {

    //
    override func loadView() {
        super.loadView()
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //弹出提示
        SVProgressHUD.showWithStatus("正在加载...")
        self.view.backgroundColor = UIColor.whiteColor()
        //设置导航栏的标题
        navigationItem.title = "登录"
        //设置两边item
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        //加载数据到webview
        let string = oauthURLString + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
//        print("\(string)")
        let url =  NSURL(string: string)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
 // MARK : - 导航栏按钮的点击操作
    func autoFill(){
    let jsString = "document.getElementById('userId').value='13560472171';document.getElementById('passwd').value='729729';"
        //使用webview调用JS代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }

 /// 懒加载 webview
    lazy var webView: UIWebView = UIWebView()
   
}
// MARK: - 扩展
extension CPOauthViewController: UIWebViewDelegate {
    //webview的代理方法
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //webivew每次加载新的数据都会走这个代理方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let url = request.URL
//        print("\(url)")
        if !url!.absoluteString.hasPrefix(redirect_uri) {
        
            //如果前缀不是redirect_uri,加载数据的界面
        
            return true
        }
        else
        {
            //如果前缀是redirect_uri,不加载数据的界面,截取code
            //得到?后面的url
            let query = url!.query!
            let codePre = "code="
            if query.hasPrefix(codePre)
            {
                //说明点击授权
                //如果query前缀是code=,截取后面的字符串,得到code
                let code = (query as NSString).substringFromIndex(codePre.characters.count)
//                print("\(code)")
                //加载AccessToken,字典转模型,模型保存到沙盒
                //定义闭包
                let callBack = {(error: NSError?) -> () in
                
                    if error != nil
                    {
                    
                        SVProgressHUD.showWithStatus("你的网络不给力...")
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), {() -> () in
                            
                            self.close()
                            });
                    }
                    else
                    {
                        //没有错误
                        self.close()
                        //跳转欢迎控制器
                        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
                        appDelegate.switchRootViewController(CPWelcomeViewController())
                        
                    }
                }
                CPUserAccountViewModel.sharedAccountViewModel.loadAccessToken(code,callBack: callBack)
            }
            else
            {
                //说明点击取消
                close()
            }
        
            return false
        }
    }
    
}
